﻿using System.Text;
using WeifenLuo.WinFormsUI.Docking;
using Koala.Pro.CodeGenerator.UI.Common;
using Koala.Pro.CodeGenerator.UI.DatabaseModel.Schema;

namespace Koala.Pro.CodeGenerator.UI
{
    public partial class FrmTableInfo : DockContent
    {
        public string DbName { get;set; }

        public string TableName { get; set; }

        private IDictionary<string, ColumnInfo> columnList;

        public IDictionary<string, ColumnInfo> ColumnList
        {
            get
            {
                return columnList;
            }
            set
            {
                if (value != null)
                {
                    columnList = value;
                    dataGridView1.DataSource = BasicTableInfoHelper.GetBasicInfo(value);
                    btnSetColumnAlias.Enabled = true;
                }
            }
        }

        public FrmTableInfo()
        {
            InitializeComponent();

            AddDynamicMenuItem();
            CreateGridViewColumns();
        }

        private void AddDynamicMenuItem()
        {
            string[] codeFormatType = FormatCodeHelper.CodeFormatType;
            foreach (string text in codeFormatType)
            {
                ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem(text);
                toolStripMenuItem.Click += menu_ChangeFormat_Click;
                menu_ChangeFormat.DropDownItems.Add(toolStripMenuItem);
            }
        }

        private void CreateGridViewColumns()
        {
            dataGridView1.Columns.Add(BuildColumn("Ordinal", "编号"));
            dataGridView1.Columns.Add(BuildColumn("Name", "名称"));
            dataGridView1.Columns.Add(BuildColumn("DataType", "数据类型"));
            dataGridView1.Columns.Add(BuildColumn("Length", "长度"));
            dataGridView1.Columns.Add(BuildColumn("PrimaryKey", "主键"));
            dataGridView1.Columns.Add(BuildColumn("AutoIncrement", "自增"));
            dataGridView1.Columns.Add(BuildColumn("AllowNull", "可空"));
            dataGridView1.Columns.Add(BuildColumn("DefaultValue", "默认值"));
            dataGridView1.Columns.Add(BuildColumn("Alias", "别名"));
            dataGridView1.Columns.Add(BuildColumn("Description", "字段描述"));
        }

        private DataGridViewTextBoxColumn BuildColumn(string name, string headerText)
        {
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn.HeaderText = headerText;
            dataGridViewTextBoxColumn.Name = name;
            dataGridViewTextBoxColumn.DataPropertyName = name;
            dataGridViewTextBoxColumn.ReadOnly = true;
            return dataGridViewTextBoxColumn;
        }

        private void menu_ChangeFormat_Click(object sender, EventArgs e)
        {
            string type = ((ToolStripMenuItem)sender).Text;
            string text = txtCodeEditor.Text;
            FormatCodeHelper.FormatText(txtCodeEditor, type, text);
        }

        private void menu_CloseAll_Click(object sender, EventArgs e)
        {
            Program.global.CloseAllDocuments();
        }

        private void menu_SaveFile_Click(object sender, EventArgs e)
        {
            var dialog = new SaveFileDialog();
            dialog.InitialDirectory = Directory.GetCurrentDirectory();
            dialog.FileName = Text;
            dialog.Filter = "sql files (*.sql)|*.sql|CSharp files (*.cs)|*.cs|All files (*.*)|*.*";
            if (DialogResult.OK == dialog.ShowDialog() && dialog.FileName.Length > 0)
            {
                txtCodeEditor.SaveFile(dialog.FileName);
                MessageUtil.ShowTips("保存成功");
            }
        }

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
            {
                dataGridView1[i, e.RowIndex].ToolTipText = string.Empty;
            }
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
                {
                    DataGridViewCell dataGridViewCell = dataGridView1.Rows[e.RowIndex].Cells[1];
                    if (dataGridViewCell.Value != null)
                    {
                        ColumnInfo columnInfo = columnList[dataGridViewCell.Value.ToString()];
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.AppendFormat("{0}：\r\n\t", "字段详细信息");
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "所属表名称", columnInfo.ParentTable.Name.Name.ToString());
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "名称", columnInfo.Name.Name.ToString());
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "别名", columnInfo.Name.Alias.ToString());
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "数据类型", columnInfo.DataType);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "DotNet类型", columnInfo.NetType.Name.ToString());
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "长度", columnInfo.MaxLength);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "主键", columnInfo.IsPrimaryKey);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "自增", columnInfo.AutoIncrement);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "可空", columnInfo.AllowDBNull);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "默认值", columnInfo.DefaultValue);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "字段描述", columnInfo.Description);
                        stringBuilder.AppendFormat("{0}：{1}\r\n\t", "字段外键信息", columnInfo.FKReference);
                        dataGridView1[i, e.RowIndex].ToolTipText = stringBuilder.ToString();
                    }
                }
            }
            catch
            {
            }
        }

        private void btnSetColumnAlias_Click(object sender, EventArgs e)
        {
            var setColumnAliasForm = new FrmSetColumnAlias();
            setColumnAliasForm.TableName = TableName;
            int num = dataGridView1.RowCount * 25;
            int num2 = setColumnAliasForm.Size.Height;
            if (num + 60 > setColumnAliasForm.Size.Height)
            {
                num2 = num + 60;
            }
            setColumnAliasForm.Size = new Size(setColumnAliasForm.Size.Width, num2);
            for (int i = 0; i < dataGridView1.RowCount - 1; i++)
            {
                Label label = new Label();
                label.Height = 40;
                label.TextAlign = ContentAlignment.MiddleRight;
                label.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                label.Text = dataGridView1.Rows[i].Cells["Name"].Value.ToString();

                TextBox textBox = new TextBox();
                textBox.Height = 40;
                textBox.Name = dataGridView1.Rows[i].Cells["Name"].Value.ToString();
                textBox.Text = dataGridView1.Rows[i].Cells["Alias"].Value.ToString();
                textBox.Tag = dataGridView1.Rows[i].Cells["Alias"].Value.ToString();

                textBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                setColumnAliasForm.tableLayoutPanel1.Controls.Add(label);
                setColumnAliasForm.tableLayoutPanel1.Controls.Add(textBox);
            }
            if (DialogResult.OK == setColumnAliasForm.ShowDialog() && setColumnAliasForm.IsDirty)
            {
                //ColumnNameAliasInfo.ColumnNameAliasTable = null;
                OnRefresh();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            OnRefresh();
        }

        private void OnRefresh()
        {
            ColumnList = Program.global.DbInstance.DatabaseList[DbName].TableList[TableName].ListColumns();
        }
    }
}
